//
//  ViewController.swift
//  Demo-14 获取用户位置
//
//  Created by quanhao huang on 2019/10/22.
//  Copyright © 2019 demo. All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate{
    
    var locationManager = CLLocationManager()
    @IBOutlet weak var latitudeLabel: UITextField!
    @IBOutlet weak var longitudeLabel: UITextField!
    @IBOutlet weak var locationErrorLable: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.delegate = self as CLLocationManagerDelegate
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        locationErrorLable.isHidden = true
        
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationErrorLable.isHidden = true
        let location = locations.last!
        
        let latitude = location.coordinate.latitude
        let longitude = location.coordinate.longitude
        
        latitudeLabel.text = String(format: "Latitude: %.4f", latitude)
        longitudeLabel.text = String(format: "longitude: %.4f", longitude)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        locationErrorLable.isHidden = false
        locationErrorLable.text = (error as! String)
    }

}

